package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.ClazzQueryParam;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService {
    @Autowired
    private EmpService empService;
    @Autowired
    private EmpMapper empMapper;

    @Override
    public PageResult<Clazz> queryClazzPage(ClazzQueryParam param) {
        Page<Clazz> page = Page.of(param.getPage(), param.getPageSize());
        page.addOrder(OrderItem.desc("update_time"));

        String name = param.getName();
        LocalDate begin = param.getBegin();
        LocalDate end = param.getEnd();

        Page<Clazz> p = lambdaQuery().like(name != null && !name.isEmpty(), Clazz::getName, name)
                .ge(begin != null, Clazz::getBeginDate, begin)
                .le(end != null, Clazz::getEndDate, end)
                .page(page);

        List<Clazz> clazzs = p.getRecords();
        if (!clazzs.isEmpty()) {
            List<Long> ids = p.getRecords().stream().map(Clazz::getMasterId).toList();
            List<Emp> emps = empService.listByIds(ids);
            Map<Long, String> idToEmp = emps.stream().collect(Collectors.toMap(Emp::getId, Emp::getName));
            clazzs.forEach(clazz -> {
                if (clazz.getMasterId() != null) {
                    clazz.setMasterName(idToEmp.get(clazz.getMasterId()));
                }
            });
            clazzs.forEach(clazz -> clazz.setStatus(getStatusByTime(clazz.getBeginDate(), clazz.getEndDate())));
        }


        return new PageResult<Clazz>(p.getTotal(), clazzs);
    }

    @Override
    public void saveClazz(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        save(clazz);
    }

    @Override
    public void updateClazz(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        updateById(clazz);
    }

    public String getStatusByTime(LocalDate begin, LocalDate end) {
        LocalDate now = LocalDate.now();
        String res;
        if (now.isBefore(begin)) {
            res = "未开课";
        } else if (now.isAfter(end)) {
            res = "已结课";
        } else {
            res = "在读";
        }
        return res;
    }
}
